#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "Comm.hpp"
#include "Inetaddr.hpp"

using namespace LogModule;
const static int gsockfd = -1;
const static uint16_t defaultport = 8080;
// const static std::string defaultip = "127.0.0.1";

using func_t = std::function<std::string(const std::string&)>;

class UdpServer
{
public:
    UdpServer(func_t func, const uint16_t port = defaultport) // 缺省参数位置
        : _sockfd(gsockfd)
        , _addr(port)
        , _func(func)
        , _isrunning(false)
    {}
    void InitUdpServer()
    {
        //1.创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERROR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is: " << _sockfd;

        // //2.填充网络信息，并绑定
        // struct sockaddr_in local;
        // bzero(&local, sizeof(local));
        // local.sin_family = AF_INET;
        // // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 转4字节IP，同时转为网络序列
        // local.sin_port = htons(_port);  // 转网络序列
        // local.sin_addr.s_addr = INADDR_ANY;

        //3.设置进内核中
        int n = bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERROR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void Start()
    {
        _isrunning = true;
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            char inbuffer[1024];
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len);
            if (n > 0)
            {
                inbuffer[n] = 0;
                // uint16_t clientport = ntohs(peer.sin_port);
                // std::string clientip = inet_ntoa(peer.sin_addr);
                // InetAddr client(peer);
                // std::string clientinfo = client.Ip() + ": " + std::to_string(client.Port()) + "# " + inbuffer;
                // LOG(LogLevel::DEBUG) << clientinfo;

                std::string str = _func(inbuffer);
                
                // std::string echo_string = "echo# ";
                // echo_string += inbuffer;
                sendto(_sockfd, str.c_str(), str.size(), 0, CONV(&peer), len);
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            close(_sockfd);
    }
private:
    int _sockfd;
    InetAddr _addr;
    // uint16_t _port;          // 服务器端口号
    // // std::string _ip;         // 服务器IP
    func_t _func;                 // 业务，回调方法
    bool _isrunning;        
};